<?php
namespace submodule\base;

use Yii;
//use backend\modules\mobo\models\BackendMenu;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;


use submodule\models\Models;
use submodule\models\ModelsField;
use common\components\Tree;
use base\YiiMobo;

use \common\models\DIYModel;

class BaseSubmodelController extends BaseSubmoduleController
{

	
	
	
	public function init(){
		
		parent::init();
		
		$this->submodel = (object)null;
		$this->submodel->default_field = [];
		
		
		if (isset($_REQUEST['modelid'])){
			$this->submodel->modelid = $_REQUEST['modelid'];
		}else{
		    $sql="SELECT `modelid` FROM `submodule_models` where `type` = '{$this->module->id}' and `isdefault` = 1";
			$this->submodel->modelid = Yii::$app->db->createCommand($sql)->queryScalar();
		}
		if (!$this->submodel->modelid){
		    exit('not found this default model');	
			
		}
		$this->submodel->models = Yii::$app->FileCache->get('submodule_model_'.$this->submodel->modelid);
		//print_r($this->submodel->models);exit;
		$this->submodel->allowinput_fields = $this->submodel->models['allowinput_fields'];
		$this->submodel->fields = $this->submodel->models['fields'];
		$this->submodel->primarykey =  $this->submodel->models['primarykey'];
		
		//$this->submodel->models['models'] = $this->submodel->models['models']['models'];
		$this->submodel->tablename = '{{%'.$this->submodel->models['models']['tablename'].'}}';
		
		$this->submodel->data_tablename = isset($this->submodel->models['models']['data_tablename']) ? $this->submodel->models['models']['data_tablename'] : '{{%'.$this->submodel->models['models']['tablename'].'_data}}';

		$this->submodel->controllerUrl = [
		    'index'=> $this->module->id.'/index/index',
			'create' => $this->module->id.'/index/create',
			'update'=> $this->module->id.'/index/update',
			'batch'=> $this->module->id.'/index/batch',
			'view'=> $this->module->id.'/index/view',
			'delete'=> $this->module->id.'/index/delete',
			'status'=> $this->module->id.'/index/status',
			'linkage'=> $this->module->id.'/index/linkage',
		];
				//视图
		$this->submodel->viewFiles = [
		    'index'=> @$this->submodel->models['models']['setting']['index']['views'],
		    'form'=> @$this->submodel->models['models']['setting']['index']['views'],
			

		];
		
		
		
	}

	/**
	 * 获取action的url
	 */
    public function getSubmodelActionUrl($action, $returnUrl = true){
		$url = isset($this->submodel->controllerUrl[$action[0]]) ? $this->submodel->controllerUrl[$action[0]] : false;
		$url = str_replace($action[0] , $url, $action);
		if ($returnUrl){
			$url = $this->createUrl($url);
		}
		return $url;
		
	}
	/**
	 * 设置视图文件
	 */
    public function setViewFiles($views){
		foreach($views as $k=>$view){
		    $this->submodel->viewFiles[$k]  = $view;
		}
	}
	
	/**
	 * 获取视图文件
	 */
    public function getViewFiles($action = 'index'){
		$viewfile = isset($this->submodel->viewFiles[$action]) ? $this->submodel->viewFiles[$action] : false;
		if (!$viewfile){
			$viewfile = "@submodule/views/submodel/submodel_".$action;
		}
		return $viewfile;
		
	}
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionCreate($parentid = 0)
	{
		$model =  (object)null;
		//print_r($this->submodel->fields);exit;
		foreach($this->submodel->fields as $v){
			$value = isset($v['setting']['defaultvalue']) ? $v['setting']['defaultvalue'] : '';
            //$model->{$v['field']} = $value;
			$model->attributes[$v['field']] = $value;
        }
		
		if($this->submodel->models['models']['type'] == 'category'){
			$model->parentid = $model->attributes['parentid'] = $parentid;
		}
        if(isset($_POST['Models']))
		{
			$this->submodelSaveForm();
		}

		return $this->render($this->getViewFiles('form'), [
		    'model'=> $model,
		    'submitUrl'=> self::getSubmodelActionUrl(['create']),
		]);
	}
	
	/**
	 * 添加数据内容.
     * 添加数据库内容的表单提交处理
	 * 模板文件通常为  views/category/_form.php
	 */
	public function actionUpdate($id)
	{
        if(isset($_POST['Models']))
		{
			$this->submodelSaveForm($id);
		}
		
		$model = $this->selectModel($id);
		return $this->render($this->getViewFiles('form'), [
		    'model'=> $model,
			'submitUrl'=> self::getSubmodelActionUrl(['update', 'id'=> $id]),
		]);
	}

	/**
	 * 查看
	 */
	public function actionView($id)
	{

		$model = $this->selectModel($id);
        $viewfile = $this->getViewFiles('view');
        //print_r($this->submodel->fields);exit;
		return $this->render($viewfile,[
		    'model'=> $model,
		    'models'=> $this->submodel->models,
		    'headerPlugins'=> $this->headerPlugins(),
			'modelid' => $this->submodel->modelid,
			'formFields' => $this->formFields(),
			'fields' => $this->submodel->fields,
		]);
	}
	/**
	 * 查出数据
	 */
    public function selectModel($id){
		$sql="SELECT * FROM {$this->submodel->tablename} a";
		if($this->checkTableName($this->submodel->data_tablename)){
			$sql .= " inner join {$this->submodel->data_tablename} b on a.`{$this->submodel->primarykey}` = b.`{$this->submodel->primarykey}`";
		}
		$sql .= " where a.`{$this->submodel->primarykey}` = $id";
		
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		$model = (object)$data;
		$model->attributes = $data;
		return $model;
	}

	
	public function updateCategory(){
		
		
	}

	
	/**
	 * 联动字段处理
	 */
	public function actionLinkage(){
		$table = $_GET['table'];
		$conditionfield = $_GET['conditionfield'];
		$value = $_GET['value'];
		$field = $_GET['field'];
		$name = $_GET['name'];
		$sql="SELECT * FROM $table where `$conditionfield` = $value";
		$data = Yii::$app->db->createCommand($sql)->queryAll();
		$rows = [];
		foreach($data as $v){
			
		}
		$tree = new \common\components\Tree;
		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ','&nbsp;&nbsp;&nbsp;├─ ','&nbsp;&nbsp;&nbsp;└─ ');
		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';
		$str = "<option value=\$id \$selected>\$spacer\$name</option>";
		$tree->init($data);
        $tr['option'] = $tree->get_tree(0,$str, 0);
		//echo $tr;
		echo json_encode($tr, JSON_UNESCAPED_UNICODE);
	}
	/**
	 * 显示数据内容
     * 改变了默认的方法，读取数据、传递参数、分页更为自由
     * 模板文件默认为 views/category/index.php
	 */
	public function actionIndex(){
		if (!$this->getSubmodelIndexFields()){
			$this->OperTips(['backurl'=> $this->createUrl(['models/update', 'modelid'=>$this->submodel->modelid]), 'error'=> true, 'title'=> '请先进行后台设置', 'timeout'=> 3000]);
		}
		if ($this->submodel->models['models']['type'] == 'category'){
			$this->actionIndexCategory();
			
		}else if ($this->submodel->models['models']['type'] == 'content'){
		    $this->actionIndexContent();	
		}else{
		    $this->actionIndexContent();	
		}
	}
	
	public function sqlCondition($sql, $orderby){
		return ['sql'=> $sql, 'orderby'=> $orderby];
		
	}
	
	
	public function actionIndexContent(){
		$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : NULL;
		$indexFields = $this->getSubmodelIndexFields();
		$getFields = $this->sqlFields('index');
		$fields = $getFields['fields'];
		$sql = $getFields['sql'];
		//exit($sql);
/*        $fields = ["a.`{$this->submodel->primarykey}`"];
        foreach($indexFields as $k=>$v){
			if ($v['primarytable'] == 2) continue;
            $fields[] = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';    
        }
        $fields = join(', ',$fields);
		$sql = "SELECT $fields FROM {$this->submodel->tablename} a";
		if (strpos($fields,'b.`') && $this->checkTableName($this->submodel->data_tablename)){
            $sql .= " inner join {$this->submodel->data_tablename} b on a.`{$this->submodel->primarykey}` = b.`{$this->submodel->primarykey}`";
		}
		$sql .= ' where 1 = 1';*/
		$search_sql = [];
		if (isset($search['keyword'])){
			foreach($this->submodel->fields as $v){
				if (isset($v['setting']['search']) && $v['setting']['search']){
					$field = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`';
					$search_sql[] = " $field like '%".$search['keyword']."%'";
				}
			}
		}
		if ($search_sql){
			$search_sql = ' and ('.join(' or ', $search_sql).')';
		}else{
			$search_sql = '';
		}
		$sql .= $search_sql;
		if (isset($search['starttime']) && $search['starttime']) $sql .= " and a.`addtime` >= ".strtotime($search['starttime']);
		if (isset($search['endtime']) && $search['endtime']) $sql .= " and a.`addtime` <= ".strtotime($search['endtime']);

        
        $orderby = isset($_REQUEST['orderby']) ? $_REQUEST['orderby'] : "a.`{$this->submodel->primarykey}` desc";
        $orderby = ' order by '.$orderby;
		$sqls = $this->sqlCondition($sql, $orderby);
        $viewfile = $this->getViewFiles('index');
        //exit($sqls['sql']);
		echo $this->render($viewfile, array_merge(YiiMobo::pageRows($sqls['sql'], $sqls['orderby']), [
		    'search'=>$search,
		    'orderby' => explode(' ', $sqls['orderby']),
		]));
		
	}
	
	public function actionGetData($modelid, $parentid = 0){
		$sql="SELECT * FROM {$this->submodel->tablename} where parentid = $parentid order by listorder asc,id asc";
		$data['modelid'] = $modelid;
		$data['data'] = Yii::$app->db->createCommand($sql)->queryAll();
		$data['depth'] = $this->CategoryDepth($parentid);
		$data['count'] = count($data['data']) - 1;
		foreach($data as $k=>$v){
			
			//$data[$k]['depth'] = $this->CategoryDepth($v['id']);
		    	
		}
		echo json_encode($data, JSON_UNESCAPED_UNICODE);
	}
	
	public function CategoryDepth($modelid, $myid, &$newarr = []){
		//global $newarr;
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		$tablename = '{{%'.$models['models']['tablename'].'}}';
		$sql="SELECT parentid FROM {$tablename} where id = $myid";
		$data = Yii::$app->db->createCommand($sql)->queryOne();
		if(!$data){
			//$newarr = [];
			 return false;
		}
		$parentid = $data['parentid'];
        $newarr[] = $parentid;
		
		if($parentid){
		    $this->CategoryDepth($modelid, $parentid, $newarr);
		}
        
		return array_reverse($newarr);
	}
	public function CategoryChildren($modelid, $myid){
		$models = Yii::$app->FileCache->get('submodule_model_'.$modelid);
		$tablename = '{{%'.$models['models']['tablename'].'}}';
		$sql="SELECT id FROM {$tablename} where FIND_IN_SET('$myid', depth)";
		return (int)Yii::$app->db->createCommand($sql)->queryAll();
	}

	public function actionDelete($modelid, $id){
		if ($this->submodel->models['models']['type'] == 'category'){
			$sql="SELECT id FROM {$this->submodel->tablename} where parentid = $id";
			if(Yii::$app->db->createCommand($sql)->queryOne()){
				$this->OperTips(['backurl'=> '', 'error'=> true, 'title'=> '不能删除有子级分类的数据', 'timeout'=> 3000]);
			}
			
		}else if ($this->submodel->models['models']['type'] == 'content'){
			$return = Yii::$app->db->createCommand()->delete($this->submodel->data_tablename, 'id = '.$id)->execute();
		}
		    $return = Yii::$app->db->createCommand()->delete($this->submodel->tablename, 'id = '.$id)->execute();
		if ($this->submodel->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
    /**
     * 更改状态设置
     * 
     */
    public function actionStatus($id, $field = 'status', $status) {
        $sql = "update {$this->submodel->tablename} set `$field` = $status where id = '$id'";
        Yii::$app->db->createCommand($sql)->query();
		$this->updateCategoryCache();
    }
	
	/**
	* 更新分类数据缓存
	*
	*/
    public function updateCategoryCache($return = false){
    	if ($this->submodel->models['models']['type'] != 'category') return false;
        if (intval($this->submodel->models['models']['setting']['index']['ajax']) == 0){
			$sql="SELECT * FROM {$this->submodel->tablename} order by listorder asc, id desc";
			$data = Yii::$app->db->createCommand($sql)->queryAll();
			
			$array = array();
			foreach($data as $k=>$v){
				$depth = $this->CategoryDepth($this->submodel->modelid, $v['id']);
				
				$v['depth'] = $depth;
				$array[$v['id']] = $v;
				Yii::$app->db->createCommand()->update($this->submodel->tablename, ['depth'=>join(',', $depth)], 'id = '.$v['id'])->execute();
				
			}
			Yii::$app->FileCache->set("models_data_".$this->submodel->modelid, $array);
			if ($return) return $array;
		}
	}

	
    /**
	 * 批量操作（删除）一些记录
	 * 一般来自控制器的默认方法index
	 * @param $id 一般为数据库表的主键值
	 */
	public function actionBatch(){
        $ids = isset($_POST['checked_id']) ? $_POST['checked_id'] : NULL;
        if(isset($_POST['batch_delete']) && $ids){
            if (isset($_POST['batch_delete'])){
                if ($this->submodel->models['models']['type'] == 'content'){
					Yii::$app->db->createCommand()->delete($this->submodel->tablename, ['id'=>$ids])->execute();
					$return = Yii::$app->db->createCommand()->delete($this->submodel->data_tablename, ['id'=>$ids])->execute();
				}else if ($this->submodel->models['models']['type'] == 'category'){
					$catid = [];
					foreach($ids as $id){
						$sql="SELECT id FROM {$this->submodel->tablename} where parentid = $id";
						if(!Yii::$app->db->createCommand($sql)->queryOne()){
							$catid[] = $id;
						}
					}
					Yii::$app->db->createCommand()->delete($this->submodel->tablename, ['id'=>$catid])->execute();
				}
		        
		
            }
			
        }else if(isset($_POST['batch_listorder'])){
			if (isset($_POST['listorder'])) foreach($_POST['listorder'] as $id=>$listorder){
				if (is_numeric($id)){
					$data = [
						'listorder'=>intval($listorder),
					];
					if (isset($_POST['name'][$id])) $data['name'] = $_POST['name'][$id];
					Yii::$app->db->createCommand()->update($this->submodel->tablename, $data, $this->submodel->primarykey.' = '.$id)->execute();
				}
			}
		}else if(isset($_POST['batch_create'])){
			if(isset($_POST['add_ame'])) foreach($_POST['add_ame'] as $k=>$v){
				if (!$v) continue;
				$data = [
				    'name' => $v,
					'parentid' => $_POST['add_pid'][$k],
					'listorder' => $_POST['add_listorder'][$k],
				];
				Yii::$app->db->createCommand()->insert($this->submodel->tablename, $data)->execute();
				$insertid = Yii::$app->db->getLastInsertID();
				if($this->submodel->models['models']['type'] == 'category'){
					$depth = $this->CategoryDepth($this->submodel->modelid, $insertid);
					Yii::$app->db->createCommand()->update($this->submodel->tablename, ['depth'=> join(',', $depth)], $this->submodel->primarykey.' = '.$insertid)->execute();	
					//exit($depth);				
				}
			}
		}
		
        if ($this->submodel->models['models']['type'] == 'category'){	
			$this->updateCategoryCache();
		}
		
		$this->OperTips();
	}
	public function actionConfig($modelid, $module)
	{
		$tablename = 'submodule_module';
		if(isset($_POST['Module']))
		{
			$data['setting'] = json_encode($_POST['Module'], JSON_UNESCAPED_UNICODE);
			Yii::$app->db->createCommand()->update($tablename, $data, "module = '$module'")->execute();
			$this->OperTips();
		}
        $sql="SELECT setting FROM `$tablename` where module = '$module'";
		$model = json_encode(Yii::$app->db->createCommand($sql)->queryOne(), true);
		return $this->render('config',[
		    'modelid' => $modelid,
			'module'=> $module,
			'model'=>$model
		]);
	}
	
	
	public function actionCheckUnique($field, $value, $pk = ''){

		$sql="select count(*) from {$this->submodel->tablename} where `$field` = '$value'";
		$sql .= $pk ? " and `{$this->submodel->primarykey}` != ".$pk : '';
		if(!Yii::$app->db->createCommand($sql)->queryScalar()){
			echo 'true';
		}else{
			echo 'false';
		}
	}
	
	public function getSubmodelIndexFields(){
		$fields = array();
		if (isset($this->submodel->models['models']['setting']['index'])) foreach($this->submodel->models['models']['setting']['index']['listorder'] as $k=>$val){
			if(isset($this->submodel->fields[$val]) && in_array($this->submodel->fields[$val]['field'], $this->submodel->models['models']['setting']['index']['fields'])){
				$value = $this->submodel->fields[$val];
				//$value['_values'] = 
				$fields[$val] = $value;
			}
		}
		return $fields;
	}


	public function listorderFields(){
	    
	    $fields = array_diff($this->submodel->fields, $this->submodel->models['models']['setting']['index']['listorder']);
		
	}
	
	/**
	*  首页字段
	*/
	public function sqlFields($action = 'index'){
		$fields = [];
		$jointable = [];
		$onfield = [];
		$apiFields = $this->submodel->models['models']['setting'][$action]['fields'];
		$modelsFields = $this->submodel->models['fields'];
		$fields['*'] = ["a.`{$this->submodel->primarykey}`"];
		$indexFields = [];
		$joinwith = $this->submodel->models['models']['setting'][$action]['joinwith'];
		foreach($modelsFields as $k=>$v){
			if (in_array($v['field'], $apiFields) && $v['primarytable'] != 2){
				$fields['*'][] = ($v['primarytable'] ? 'a' : 'b').'.`'.$v['field'].'`'; 
				$indexFields[$v['field']] = $v;
			}
			$fields[$v['field']] = $v; 
		}
		foreach($fields as $k=>$v){
			if ($k == '*' || !isset($joinwith[$k])) continue;
			$jointype = $joinwith[$k]['jointype'];
			$joinfield = $joinwith[$k]['joinfield'];
			$table = $joinwith[$k]['table'];
			$field = $joinwith[$k]['field'];
			
			if ($joinfield && $field && $table){
				foreach(explode(',', $field) as $fd){
				   $fields['*'][] = "$table.`$fd`";
				}
				$jointable[] = "  {$jointype} {$table} on a.`$k` = $table.`$joinfield`";
				$indexFields[$k]['field'] = $field;
			}
		}
		$fields['*'] = join(', ',$fields['*']);

		$sql = "SELECT {$fields['*']} FROM {$this->submodel->tablename} a";
		
		if (strpos($fields['*'],'b.`')){
			$sql .= " inner join {{%{$this->submodel->tablename}_data}} b on a.`{$this->submodel->primarykey}` = b.`{$this->submodel->primarykey}`";
		}
		foreach($jointable as $tb){
			$sql .= $tb; 
		}
		$fields['+'] = $indexFields;
		//print_r($fields);
		//exit;
		return ['fields'=> $fields, 'jointable'=> $jointable, 'sql'=> $sql];
	}
	


}
